package chances.epg.commons.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public class RequestUtils {
	
	
	public static String getRequestPath(HttpServletRequest request) {
		return (String) request.getAttribute("javax.servlet.forward.request_uri");
	}
	/**
	 * 得到Long 
	 * @param request
	 * @param name
	 * @param defValue
	 * @return
	 */
	public static long getParameter(HttpServletRequest request, String name,
			long defValue) {
		String value = request.getParameter(name);
		if (StringUtils.isNotEmpty(value) || StringUtils.isNumeric(value)) {

			return Long.parseLong(value);

		} else {
			return defValue;
		}
	}
	
	public static int getParameter(HttpServletRequest request, String name,
			int defValue) {
		String value = request.getParameter(name);
		if (StringUtils.isNotEmpty(value) && StringUtils.isNumeric(value)) {
			return Integer.parseInt(value);
		} else {
			return defValue;
		}
	}
	
	public static String getParameter(HttpServletRequest request, String name,String  defValue) {
		String value = request.getParameter(name);
		if (StringUtils.isNotEmpty(value)) {
			return  value;
		} else {
			return defValue;
		}
	}
	
	public static boolean getParameter(HttpServletRequest request, String name,boolean  defValue) {
		String value = request.getParameter(name);
		if (StringUtils.isNotEmpty(value)) {
			return  Boolean.parseBoolean(value);
		} else {
			return defValue;
		}
	}
	
	/**
	 * 得到Long 
	 * @param request
	 * @param name
	 * @param defValue
	 * @return
	 */
	public static Date getDateParameter(HttpServletRequest request, String name,String format) {
		String value = request.getParameter(name);
		if (StringUtils.isNotEmpty(value)) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(format);
			try {
				return dateFormat.parse(value);
			} catch (ParseException e) {
				return null;
			}
		} else {
			return null;
		}
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	public static String getRemoteIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * 读取请求内容.
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String readRequestInputStream(HttpServletRequest request) throws IOException {
    	InputStream is = null;
		String body = "";
		try {
			is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			String buffer = null;
			StringBuffer sb = new StringBuffer();
			while ((buffer = br.readLine()) != null) {
				sb.append(buffer);
			}

			body = sb.toString();
		}finally{
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {

			}
		}
		
		return body;
    }
	
	public static String post(String json, String urlLocation) throws Exception{
    	URL url = new URL(urlLocation);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setConnectTimeout(1000 * 5);
        connection.setRequestProperty("Content-Type", "textml;charset=UTF-8");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setRequestProperty("Charset", "UTF-8");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        StringBuffer body = new StringBuffer();
        OutputStream os = null;
        InputStream is = null;
        try {
            os = connection.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.flush();
            os.close();
            if (connection.getResponseCode() == 200) {
                String line = null;
                is = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        is, "UTF-8"));
                while ((line = br.readLine()) != null) {
                    body.append(line);
                }
                return body.toString();
            }else{
            	return "";
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }
    }
}
